//
//  main.cpp
//  DayTimeClient1
//
//  Created by Ge Jian Feng on 14-5-24.
//  Copyright (c) 2014年 Ge Jian Feng. All rights reserved.
//

#include <iostream>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>

// Define
#define MAXLINE                 4096
#define bzero(addr,len)         memset(addr, 0, len)

int main(int argc, const char * argv[])
{
    // Initialize variable
    int                 socketId;
    char                recvline[MAXLINE + 1];
    struct sockaddr_in  servaddr;
    ssize_t             n;
    int                 status;
    
    // Check IP Address Param
    if (argc != 2) {
        std::cerr << "Missing IP address!" << std::endl;
        exit(1);
    }
    
    // Create socket
    socketId = socket(AF_INET, SOCK_STREAM, 0);
    if (socketId < 0) {
        std::cerr << "Create socket error!" << std::endl;
        exit(1);
    }
    
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(13000);
    servaddr.sin_addr.s_addr = inet_addr(argv[1]);
    servaddr.sin_len = sizeof(servaddr);
    bzero(&servaddr.sin_zero, sizeof(servaddr.sin_zero));
    
    // Connect socket
    status = connect(socketId, (struct sockaddr*)&servaddr, sizeof(servaddr));
    if (status < 0) {
        std::cerr << "Connect error!" << std::endl;
        exit(1);
    }
    
    // Process logic
    while ((n = read(socketId, recvline, MAXLINE)) > 0) {
        recvline[n] = 0;
        if (fputs(recvline, stdout) == EOF) {
            std::cerr << "Fputs error!" << std::endl;
            exit(1);
        }
    }
    
    if (n < 0) {
        std::cerr << "Read error!" << std::endl;
        exit(1);
    }
    
    return 0;
}

